package email

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/sredis"
	"gitee.com/bobo-rs/innovideo-services/consts"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
	"time"
)

// SaveTemplate 保存邮件模板数据
func (e *sEmail) SaveTemplate(ctx context.Context, en entity.EmailTemplate) error {
	// 根据缓存变量获取模板ID
	if en.Id == 0 {
		detail, _ := e.QueryTemplateDetailByVarName(ctx, en.VarName)
		if detail != nil {
			en.Id = detail.Id
		}
	}

	// 保存模板数据
	err := e.TemplateModel().Save(ctx, en)
	if err != nil {
		return exception.Newf(`保存邮件模板失败%s`, err.Error())
	}
	// 清除缓存
	e.RemoveCache(ctx, en.VarName)
	return nil
}

// GetTemplateList 获取邮件模板列表
func (e *sEmail) GetTemplateList(ctx context.Context, in model.EmailTemplateListInput) (out *model.EmailTemplateListOutput, err error) {
	out = &model.EmailTemplateListOutput{}
	var (
		orm = dao.EmailTemplate.Ctx(ctx)
	)
	if in.Name != `` {
		orm = orm.Where(dao.EmailTemplate.Columns().Name, in.Name)
	}
	// 变量名
	if in.VarName != `` {
		orm = orm.Where(dao.EmailTemplate.Columns().VarName, in.VarName)
	}
	err = orm.OrderDesc(dao.EmailTemplate.Columns().Id).
		Page(in.Page, in.Size).
		ScanAndCount(&out.Rows, &out.Total, false)
	return
}

// GetTemplateByVarName 通过变量名获取邮件模板详情
func (e *sEmail) GetTemplateByVarName(ctx context.Context, varName string) (detail *model.EmailTemplateItem, err error) {
	detail = &model.EmailTemplateItem{}
	var (
		key       = consts.EmailTemplateDetailVarName + varName
		cacheFunc = func(ctx context.Context) (interface{}, error) {
			return e.QueryTemplateDetailByVarName(ctx, varName)
		}
	)

	// 获取模板详情
	r, err := sredis.NewCache().GetOrSetFunc(ctx, key, cacheFunc, time.Hour*24*7)
	if err != nil {
		return nil, err
	}
	// 扫描数据
	if err = r.Scan(&detail); err != nil {
		return nil, exception.Newf(`扫描邮件模板数据EmailTemplateItem失败 %s`, err.Error())
	}
	return
}

// QueryTemplateDetailByVarName 通过变量名查询邮件模板详情
func (e *sEmail) QueryTemplateDetailByVarName(ctx context.Context, varName string) (detail *model.EmailTemplateItem, err error) {
	detail = &model.EmailTemplateItem{}
	// 获取邮件详情
	err = e.TemplateModel().Scan(ctx, g.Map{
		dao.EmailTemplate.Columns().VarName: varName,
	}, &detail)
	return
}

// RemoveCache 移除缓存
func (e *sEmail) RemoveCache(ctx context.Context, varName string) {
	err := sredis.NewCache().Removes(ctx, []interface{}{
		consts.EmailTemplateDetailVarName + varName,
	})
	defer func() {
		if err != nil {
			g.Log().Debug(ctx, `清除邮件模板缓存失败`, err)
		}
	}()
}
